package com.javaweb.exception;

import com.javaweb.controller.common.ResponseResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import static com.javaweb.controller.common.ReturnMsgConstants.REQUEST_PARAM_ERROR;

/**
 * @desc:
 * @author: Ping
 * @date: 2024/11/6 8:36
 */

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    @ExceptionHandler({
            MissingServletRequestParameterException.class,
            MethodArgumentNotValidException.class,
            ConstraintViolationException.class,
            BindException.class
    })
    @ResponseBody
    public ResponseResult<String> handleRequestValidation(HttpServletRequest req,
                                                          Exception e){
        log.info("url:{}  error: {}", req.getRequestURI(), e.getMessage()) ;
        return ResponseResult.error(HttpStatus.BAD_REQUEST, REQUEST_PARAM_ERROR);
    }
    @ExceptionHandler(Exception.class)
    public ResponseResult<String> handleException(HttpServletRequest req, Exception e){
        log.info("url:{}  type:{}, error: {}", req.getRequestURI(),
                e.getClass().getName(), e.getMessage()) ;
        return ResponseResult.error(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
    }




}
